package com.hanxiaozhang.redisson.source;

import io.netty.util.Timeout;
import io.netty.util.TimerTask;
import io.netty.util.concurrent.FutureListener;
import org.redisson.RedissonShutdownException;
import org.redisson.api.RFuture;
import org.redisson.api.RTopic;
import org.redisson.api.listener.BaseStatusListener;
import org.redisson.api.listener.MessageListener;
import org.redisson.connection.ConnectionManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

/**
 * 功能描述: <br>
 * 〈源码阅读〉
 *
 * @Author: hanxinghua
 * @Date: 2022/9/19
 */
public abstract class MyQueueTransferTask {

    private static final Logger log = LoggerFactory.getLogger(MyQueueTransferTask.class);

    /**
     * 任务过期时间实体
     */
    public static class TimeoutTask {

        private final long startTime;
        private final Timeout task;

        public TimeoutTask(long startTime, Timeout task) {
            super();
            this.startTime = startTime;
            this.task = task;
        }

        public long getStartTime() {
            return startTime;
        }

        public Timeout getTask() {
            return task;
        }

    }

    // 使用次数
    private int usage = 1;
    private final AtomicReference<TimeoutTask> lastTimeout = new AtomicReference<TimeoutTask>();
    private final ConnectionManager connectionManager;

    public MyQueueTransferTask(ConnectionManager connectionManager) {
        super();
        this.connectionManager = connectionManager;
    }

    public void incUsage() {
        usage++;
    }

    public int decUsage() {
        usage--;
        return usage;
    }

    private int messageListenerId;
    private int statusListenerId;

    /**
     * 开始
     */
    public void start() {
        RTopic<Long> schedulerTopic = getTopic();
        // 添加监听订阅发布的事件
        statusListenerId = schedulerTopic.addListener(new BaseStatusListener() {
            @Override
            public void onSubscribe(String channel) {
                pushTask();
            }
        });

        // 添加监听消息的事件
        messageListenerId = schedulerTopic.addListener(new MessageListener<Long>() {
            @Override
            public void onMessage(CharSequence channel, Long startTime) {
                scheduleTask(startTime);
            }
        });
    }

    public void stop() {
        RTopic<Long> schedulerTopic = getTopic();
        schedulerTopic.removeListener(messageListenerId);
        schedulerTopic.removeListener(statusListenerId);
    }

    /**
     * 根据startTime计算延迟，来推送任务
     *
     * @param startTime
     */
    private void scheduleTask(final Long startTime) {
        TimeoutTask oldTimeout = lastTimeout.get();
        if (startTime == null) {
            return;
        }

        if (oldTimeout != null) {
            oldTimeout.getTask().cancel();
        }
        // 计算延迟时间
        long delay = startTime - System.currentTimeMillis();
        // 延迟大于10，启动延迟任务，否则执行启动
        if (delay > 10) {
            // 启动一个延迟任务，由netty的shHashedWheelTimer实现
            Timeout timeout = connectionManager.newTimeout(new TimerTask() {
                @Override
                public void run(Timeout timeout) throws Exception {
                    pushTask();

                    TimeoutTask currentTimeout = lastTimeout.get();
                    if (currentTimeout.getTask() == timeout) {
                        lastTimeout.compareAndSet(currentTimeout, null);
                    }
                }
            }, delay, TimeUnit.MILLISECONDS);

            // CAS 更新失败，则取消延迟任务
            if (!lastTimeout.compareAndSet(oldTimeout, new TimeoutTask(startTime, timeout))) {
                timeout.cancel();
            }
        } else {
            pushTask();
        }
    }

    protected abstract RTopic<Long> getTopic();

    protected abstract RFuture<Long> pushTaskAsync();

    /**
     * 推送任务，将到期的任务推送到阻塞队列
     */
    private void pushTask() {
        // 执行实例化时，定义的pushTaskAsync，返回结果及延迟队列队头的到期时间，
        // 即执行 com.hanxiaozhang.redisson.source.MyQueueTransferTask.pushTaskAsync
        RFuture<Long> startTimeFuture = pushTaskAsync();
        // 添加监听操作完成的事件
        startTimeFuture.addListener(new FutureListener<Long>() {
            @Override
            public void operationComplete(io.netty.util.concurrent.Future<Long> future) throws Exception {
                // 处理执行失败
                if (!future.isSuccess()) {
                    if (future.cause() instanceof RedissonShutdownException) {
                        return;
                    }
                    log.error(future.cause().getMessage(), future.cause());
                    scheduleTask(System.currentTimeMillis() + 5 * 1000L);
                    return;
                }
                // 返回当前的结果
                if (future.getNow() != null) {
                    scheduleTask(future.getNow());
                }
            }
        });
    }

}
